<template>
  <div class="messages-item">
    <!-- 问题 -->
    <div class="chat-message is-own" v-if="!currentMessage.isAnswer">
      <div class="message-content">
        <!-- 深度思考切换：只要检测到 <think> 标签就显示 -->
        <div v-if="parsedContent.hasThink" class="think-section">
          <div class="think-btn" @click="showThink = !showThink">
            <div class="think-icon">
              <el-icon :class="{ active: showThink }" :size="12">
                <ArrowRightBold />
              </el-icon>
            </div>
            <span>深度思考</span>
          </div>
          <div v-show="showThink" class="think-content">
            <template v-if="parsedContent.thinkContent">
              <MarkdownView :content="parsedContent.thinkContent" />
            </template>
          </div>
        </div>
        <div class="message-bubble own" v-if="parsedContent.visibleContent">
          <div class="message-text">
            <MarkdownView :content="parsedContent.visibleContent" />
          </div>
        </div>
      </div>
      <div class="message-avatar">
        <el-avatar :size="40" :src="currentMessage.avatar">
          <el-icon :size="20">
            <User />
          </el-icon>
        </el-avatar>
      </div>
    </div>
    <!-- 回答 -->
    <div v-if="currentMessage.isAnswer">
      <div class="chat-message">
        <div class="message-avatar">
          <el-avatar
            :size="40"
            :src="
              currentMessage.avatar ||
              'http://36.213.76.124:6060/education/pame_icon.png'
            "
          >
            <el-icon :size="20">
              <User />
            </el-icon>
          </el-avatar>
        </div>
        <div class="message-content">
          <!-- 深度思考切换：只要检测到 <think> 标签就显示 -->
          <div
            v-if="parsedContent.hasThink || isStreaming"
            class="think-section"
          >
            <div class="think-btn" @click="showThink = !showThink">
              <div class="think-icon">
                <el-icon :class="{ active: showThink }" :size="12">
                  <ArrowRightBold />
                </el-icon>
              </div>
              <span>{{ isStreaming ? "正在深度思考..." : "已深度思考" }}</span>
            </div>
            <div v-show="showThink" class="think-content">
              <template v-if="parsedContent.thinkContent">
                <MarkdownView :content="parsedContent.thinkContent" />
              </template>
            </div>
          </div>
          <div class="message-bubble" v-if="parsedContent.visibleContent">
            <div class="message-text">
              <MarkdownView :content="parsedContent.visibleContent" />
            </div>
          </div>
        </div>
      </div>
      <!-- 只有当流式结束后才显示切换与重问按钮 -->
      <ChatSwitch
        :message="currentMessage"
        v-if="!isStreaming && currentMessage.siblingCount > 1"
        @switch="switchChild"
      ></ChatSwitch>
      <div class="action-btn">
        <el-icon v-if="!isStreaming" @click="handleRefresh(currentMessage)">
          <RefreshRight />
        </el-icon>
      </div>
    </div>
  </div>
</template>

<script setup>
import MarkdownView from "./MarkdownView/index.vue";
import ChatSwitch from "./ChatSwitch.vue";
const emit = defineEmits(["switch", "refresh"]);

const props = defineProps({
  message: {
    type: Object,
    required: true,
    default: () => ({
      id: "",
      answer: "",
      avatar: "",
    }),
  },
  isStreaming: {
    type: Boolean,
    default: false,
  },
});

// 获取当前要显示的消息（原始消息或当前选中的子消息）
const currentMessage = computed(() => props.message);

// 切换到指定子消息
const switchChild = (id) => {
  emit("switch", id);
};

const handleRefresh = (message) => {
  emit("refresh", message);
};

// 深度思考解析与开关
const showThink = ref(false);
const parsedContent = computed(() => {
  const raw = (currentMessage.value?.content || "").toString();
  if (!raw) return { visibleContent: "", thinkContent: "" };

  const openTag = "<think>";
  const closeTag = "</think>";

  let cursor = 0;
  let visibleBuilder = "";
  const thinkParts = [];

  while (cursor < raw.length) {
    const openIdx = raw.indexOf(openTag, cursor);
    if (openIdx === -1) {
      visibleBuilder += raw.slice(cursor);
      break;
    }
    // append visible before think
    visibleBuilder += raw.slice(cursor, openIdx);
    const afterOpen = openIdx + openTag.length;
    const closeIdx = raw.indexOf(closeTag, afterOpen);
    if (closeIdx === -1) {
      thinkParts.push(raw.slice(afterOpen));
      cursor = raw.length;
      break;
    } else {
      thinkParts.push(raw.slice(afterOpen, closeIdx));
      cursor = closeIdx + closeTag.length;
      continue;
    }
  }

  const thinkContent = thinkParts.join("\n\n").trim();
  return {
    visibleContent: visibleBuilder.trim(),
    thinkContent,
    hasThink: raw.includes(openTag),
  };
});

watch(
  () => currentMessage.value?.id,
  () => {
    showThink.value = false;
  }
);

// 根据流式状态与是否存在思考内容自动展开/收起
watch(
  () => ({
    streaming: props.isStreaming,
    hasThink: !!parsedContent.value.thinkContent,
  }),
  ({ streaming, hasThink }) => {
    if (!hasThink) return;
    showThink.value = !!streaming;
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
.messages-item {
  padding-bottom: 20px;
  .chat-message {
    display: flex;
    margin-bottom: 16px;
    align-items: flex-start;
    position: relative;
    padding-right: 45px;
    &.is-own {
      justify-content: end;
      padding-right: 0;
      .message-content {
        align-items: flex-end;
      }
    }

    .message-avatar {
      margin: 0 8px;
      flex-shrink: 0;
    }

    .message-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: flex-start;

      .message-bubble {
        border-radius: 12px;
        padding: 5px 12px 0px;
        position: relative;
        word-wrap: break-word;

        &.own {
          background: #e1effe;
          padding: 12px 16px;
        }

        .message-text {
          :deep(br) {
            line-height: 1.4;
          }
        }
      }
    }
  }
  .action-btn {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
    padding-right: 45px;
    .el-icon {
      cursor: pointer;
    }
  }

  // 深度思考样式
  .think-section {
    width: 100%;

    .think-content {
      margin-top: 5px;
      padding: 10px 12px;
      border-left: 1px solid #10182814;
      background: #f3f3f3;
      border-radius: 0 6px 6px 0;
    }

    .think-placeholder {
      color: #6b7280;
      font-size: 13px;
    }

    .think-btn {
      font-weight: bold;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      font-size: 15px;
      padding: 5px 0;
      .think-icon {
        width: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        .el-icon {
          transition: transform 0.3s ease;
        }

        .active {
          transform: rotate(90deg);
        }
      }

      span {
        padding-left: 3px;
      }
    }
  }
}

@keyframes messageSlideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .chat-message {
    .message-content {
      max-width: 80%;
    }
  }
}
</style>
